package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果

        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public PageResponseResult getPictureList(WmMaterialDto wmMaterialDto) {
        // 参数校验
        if (wmMaterialDto == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            // 根据业务需求返回空结果或抛出异常，这里保持原逻辑
            return null;
        }

        // 构建基础查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, user.getId());

        // 添加收藏条件
        Short isCollection = wmMaterialDto.getIsCollection();
        if (isCollection != null && isCollection == (short) 1) {
            wrapper.eq(WmMaterial::getIsCollection, isCollection);
        }

        // 执行分页查询
        Page<WmMaterial> wmMaterialPage = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        Page<WmMaterial> resultPage = page(wmMaterialPage, wrapper);

        // 构建响应对象
        PageResponseResult responseResult = new PageResponseResult();
        responseResult.setData(resultPage.getRecords());
        responseResult.setCurrentPage((int) resultPage.getCurrent());
        responseResult.setSize((int) resultPage.getSize());
        responseResult.setTotal((int) resultPage.getTotal()); // 直接使用page对象的总数
        responseResult.setCode(200);

        return responseResult;

    }


//    @Override
//    public ResponseResult collect(Integer id) {
//        WmMaterial wmMaterial = new WmMaterial();
//        wmMaterial.setId(id);
//        wmMaterial.setIsCollection((short) 1);
//        updateById(wmMaterial);
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult collect(Integer id) {
        // 参数校验
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询当前状态
        WmMaterial currentMaterial = getById(id);
        if (currentMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 状态检查避免无效更新
        if (currentMaterial.getIsCollection() == 1) {
            // 修改后
            ResponseResult<WmMaterial> response = ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            response.setData(currentMaterial);
            return response;
        }

        // 使用LambdaUpdateWrapper进行条件更新
        boolean success = update(new LambdaUpdateWrapper<WmMaterial>()
                        .eq(WmMaterial::getId, id)
                        .set(WmMaterial::getIsCollection, (short) 1)
                // 添加乐观锁条件（如果表有version字段）
                // .eq(WmMaterial::getVersion, currentMaterial.getVersion())
        );

        if (!success) {
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAILED);
        }

        // 返回更新后的完整数据
        WmMaterial updatedMaterial = getById(id);
        ResponseResult responseResult = ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        responseResult.setData(updatedMaterial);
        return responseResult;
    }


    @Override
    public ResponseResult cancel_collect(Integer id) {
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short) 0);
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}